<template>
  <div class="farm-browse-container">
    <el-card body-style="padding:0px;margin:0px">
      <div class="flex-wrap">
        <div class="flex-wrap go-back" @click="handleClickBack">
          <img :src="backImg"/>
          <span style="margin-left: 10px">返回</span>
        </div>
        <div style="color:#00955b;font-weight:bolder;margin-left: 20px">农事一览</div>
      </div>
    </el-card>
    <div style="height:16px"></div>
    <el-card body-style="padding:10px;">
      <div class="flex-wrap" style="margin-left:10px">
        <el-form :inline="true" :model="formInline" style="margin-bottom: -20px">
          <el-form-item label="农事类型">
            <el-select v-model="formInline.farmType" placeholder="请选择类型" clearable>
              <el-option v-for="item in farmTypeOptions" :key="item.formCode" :label="item.formName"
                         :value="item.formCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="formInline.statusType" placeholder="请选择状态" clearable>
              <el-option v-for="item in statusTypeOptions" :key="item.statusCode" :label="item.statusName"
                         :value="item.statusCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="种植人员">
            <el-select v-model="formInline.planter" placeholder="请选择种植人员" clearable>
              <el-option v-for="item in plantersTypeOptions" :key="item.planterCode" :label="item.planterName"
                         :value="item.planterCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="地块">
            <el-select v-model="formInline.plantId" placeholder="请选择地块" clearable>
              <el-option v-for="item in plantOptions" :key="item.key" :label="item.plantName"
                         :value="item.plantCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model.trim="formInline.keyWorks" placeholder="请输入要查询的关键字" @keydown.native.enter="onSubmit"
                      clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" :loading="queryStatus">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <div style="height:16px" ref="cardContainerWidth"></div>
    <el-card :style="{height:mainCardHeight+'px'}">
      <div class="farm-browse-item-wrap" v-loading="tableLoading" :style="{maxHeight:(mainCardHeight-80)+'px'}">
        <farm-browse-item @openDetail="openDetail" :ref="'farmBrowseItem_'+item.id" v-for="item in farmBrowseItemArray"
                          :key="item.id" class="farm-browse-item"/>
      </div>
      <div class="flex-wrap" style="align-items: center;justify-content: center">
        <page-plugin
          v-show="true"
          :pages="page.pages"
          :total="page.total"
          label="农资"
          :page.sync="page.pageNo"
          :limit.sync="page.pageSize"
          @changePageNum="changePageNum"
        />
      </div>
    </el-card>
  </div>
</template>
<script>
    import PubSub from 'pubsub-js'
    import {FARM_EVENT_OPEN_DIALOG} from '@/utils/publishId'
    import farmBrowseItem from "./farm-browse-item"
    import pagePlugin from "@/components/page-plugin"
    import {
        queryLandListList
    } from '@/api/home'
    import {
        queryTaskType,
        queryPlanters,
        queryTaskStatusType,
        queryFarmEvent,
        queryFarmEventById
    } from "@/api/affairs"

    import {getUUID} from "../../../../utils";

    export default {
        components: {
            'page-plugin': pagePlugin,
            'farm-browse-item': farmBrowseItem
        },
        data() {
            return {
                tableLoading: false,
                backImg: require("@/assets/img/farm/goback.png"),
                queryStatus: false,
                page: {
                    pages: 1,
                    total: 0,
                    pageNum: 1,
                    pageSize: 10
                },
                formInline: {
                    farmType: "",
                    statusType: "",
                    planter: '',
                    plantId: "",
                    keyWorks: ""
                },
                farmTypeOptions: [],
                statusTypeOptions: [],
                plantersTypeOptions: [],
                plantOptions: [],
                mainCardHeight: 0,
                farmItemWith: 0,
                farmBrowseItemArray: []
            }
        },
        created() {
            this.$dynamic(
                window,
                document,
                258,
                (height) => {
                    this.mainCardHeight = height
                }
            );
            this.$nextTick(() => {
                this.farmItemWith = (this.$refs.cardContainerWidth.clientWidth - 74) / 2
            })
            this.getAllOptions()
        },
        beforeDestroy() {
            this.$unResize(window)
        },
        methods: {
            onSubmit() {
                this.queryStatus = true
                this.getTableList()
            },
            openDetail(item) {
                // console.log("打开内容",item)
                queryFarmEventById(item.id).then(res=>{
                    const {data, code, msg} = res.data
                    if(code==200){
                        console.log("id", item.id, data)
                        const {farmType,farmTypeId, proposal, dealTime, StockGoodsOutDetailVoList,StockMachineryOutDetailVoList} = data
                        // TODO: 测试数据，接口调通后使用  goodsList->StockGoodsOutDetailVoList  machineList->StockMachineryOutDetailVoList
                        // let tmpGoodsList = [{
                        //     materialFlag:2,
                        //     id:6,
                        //     tenantId:"__wizard_tenant__",
                        //     landId:1,
                        //     plantId:1,
                        //     taskId:14,
                        //     taskDealId:0,
                        //     materialId:"fe98c632897f4e27b6e4d216bd86ec2b",
                        //     qty:"30",
                        //     price:15000000,
                        //     total:450000000,
                        //     durationUnit:"天",  // 投入时长单位（农机专用） 整型
                        //     materialType:21,
                        //     materialName:"测试农机名称7",   // 物资名称 字符串
                        //     model:"测试型号7",   // 型号 字符串
                        //     brand:"测试品牌7",  // 品牌 字符串
                        //     specs:"30", // 规格（农资专用） 整型
                        //     unit:"台", // 计数单位 字符串
                        //     meteringUnit: "单位", //计量单位（农资专用） 字符串
                        //     supplier:"测试生产商7",
                        //     gmtCreate:"2021-06-11 09:04:11",
                        //     materialTypeName:"拖拉机/播种机/兰博基尼播种机"  // 物资分类名称 字符串
                        // }]
                        PubSub.publish(FARM_EVENT_OPEN_DIALOG, {show: true, type:"detail", item: {
                            farmTypeId: farmTypeId,
                            farmType: farmType,
                            proposal: proposal,
                            dealTime: dealTime,
                            goodsList: StockGoodsOutDetailVoList,  // tmpGoodsList
                            machineList: StockMachineryOutDetailVoList // tmpGoodsList
                        }})
                    }else{
                        this.$message({type:"error", message: msg})
                    }

                }).catch(err=>{
                    this.$message({type:"error", message: "通过id获取详情失败："+err})
                })
            },
            async getTableList() {
                const params = {
                    pageSize: this.page.pageSize,
                    pageNum: this.page.pageNum
                }
                if(this.formInline.planter && this.formInline.planter!=''){
                    params['execPersonId'] = this.formInline.planter
                }
                if(this.formInline.farmType && this.formInline.farmType!=''){
                    params['farmType'] = this.formInline.farmType
                }
                if(this.formInline.plantId && this.formInline.plantId!=''){
                    params['landNumber'] = this.formInline.plantId
                }
                if(this.formInline.statusType && this.formInline.statusType!=''){
                    params['status'] = this.formInline.statusType
                }
                if(this.formInline.keyWorks && this.formInline.keyWorks!=''){
                    params['landName'] = this.formInline.keyWorks
                }

                const response = await queryFarmEvent(params)
                const {data,code,msg} = response.data
                this.tableLoading = true
                this.page.pageNum = data.pageNum
                this.page.pageSize = data.pageSize
                this.page.total = data.total
                this.page.pages = data.pages
                this.farmBrowseItemArray = []
                if(data.list && data.list.length>0){
                    if(code==200){
                        let pointer = '未指派'
                        this.farmBrowseItemArray = data.list.map(item=>{
                            if(item.execPersonId && item.execPersonId!=''){
                                const pointerObj = this.plantersTypeOptions.find(obj=>obj.planterCode==item.execPersonId)
                                if(pointerObj && pointerObj.planterName){
                                    pointer = pointerObj.planterName +"指派"
                                }else{
                                    pointer = '未匹配'
                                }
                            }
                            const obj = {
                                id: item.id,
                                width: this.farmItemWith,
                                status: item.status,
                                money: (item.stockGoodsTotal*1+item.stockMachineryTotal*1)/100, // 分转元
                                area: item.plantArea,
                                startDate: item.startTime,
                                endDate: item.endTime,
                                name: item.landName,
                                pointer: pointer,
                                taskName: item.farmType,
                                publish: item.gmtCreate,
                                imgUrl: item.landImg
                            }
                            return obj
                        })
                        this.$nextTick(() => {
                            this.farmBrowseItemArray.forEach(item => {
                                this.$refs['farmBrowseItem_' + item.id][0].setData(item)
                            })
                        })
                        this.queryStatus = false
                        this.tableLoading = false
                    }else{
                        this.queryStatus = false
                        this.tableLoading = false
                        this.$message({type:"error", message: msg})
                    }
                }else{
                    this.queryStatus = false
                    this.tableLoading = false
                }
            },

            getAllOptions() {
                const loading = this.$load(this)
                Promise.all([queryTaskType(),queryTaskStatusType(),queryLandListList({pageSize: 9999, pageNum: 1, landName: ""}),queryPlanters()]).then(res=>{
                    //农事类型
                    if(res[0].data.code==200&&res[0].data.data && res[0].data.data.length>0){
                        this.farmTypeOptions = []
                        res[0].data.data.forEach(item=>{
                            const obj = {
                                formCode:item.dictValue,
                                formName:item.dictLabel
                            }
                            this.farmTypeOptions.push(obj)
                        })
                    }
                    //状态
                    if(res[1].data.code==200&&res[1].data.data && res[1].data.data.length>0){
                        this.statusTypeOptions = []
                        res[1].data.data.forEach(item=>{
                            const obj = {
                                statusCode:item.dictValue,
                                statusName:item.dictLabel
                            }
                            this.statusTypeOptions.push(obj)
                        })
                    }
                    //地块
                    if(res[2].data.code==200&&res[2].data.data.list && res[2].data.data.list.length>0){
                        res[2].data.data.list.forEach(item=>{
                            const obj = {
                                key: getUUID(),
                                plantCode: item.id,
                                plantName: item.landName
                            }
                            this.plantOptions.push(obj)
                        })
                    }
                    //人员
                    if(res[3].data.code==200&&res[3].data.data && res[3].data.data.length>0){
                        this.plantersTypeOptions = []
                        res[3].data.data.forEach(item=>{
                            const obj = {
                                planterCode:item.userId,
                                planterName:item.userName
                            }
                            this.plantersTypeOptions.push(obj)
                        })
                    }
                    loading.close()
                    this.getTableList()
                }).catch(err=>{
                    loading.close()
                    this.$message({type:"error", message: res.data.msg})
                })

            },
            changePageNum(val) {
                // console.log("修改页码时触发", val)
                this.page.pageNum = val.page
                this.page.pageSize = val.limit
                this.getTableList()
            },
            handleClickBack() {
                this.$emit("changePage", 1)
            }
        }
    }
</script>
<style scoped>
  .farm-browse-container {

  }

  .flex-wrap {
    display: flex;
    align-items: center;
  }

  .go-back {
    cursor: pointer;
    user-select: none;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px 10px;
    width: 80px;
    background: #f1faf7;
  }

  .farm-browse-item-wrap {
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
  }

  .farm-browse-item-wrap .farm-browse-item {
    margin-bottom: 20px;
    margin-right: 20px;
  }

  .farm-browse-item-wrap .farm-browse-item:nth-child(2n+2) {
    margin-right: 0px;
  }
</style>
